<template>
  <div style="min-width: 330px;">
    <section style="padding: 10px 20px;">
      <div>
        <label for="homeworkname">
          <div class="InputLabel">作业名 Homework Name</div>
          <input
            type="text"
            class="MyInput"
            style="
              margin: 10px;
              width: 50% !important;
              border-radius: 0.5em !important;
            "
            name="homeworkname"
            v-model="form.homeworkName"
          />
        </label>
      </div>

      <div>
        <label for="submittype">
          <div class="InputLabel">提交类型 Submit Type</div>
          <el-cascader
            class="MySelect"
            v-model="form.submitType.value"
            :options="form.submitType.options"
            @change="form.submitType.handleChange"
            name="submittype"
          />
        </label>
      </div>
      <div>
        <label for="subject">
          <div class="InputLabel" name="subject">
            学科与项目 Subject & Project
          </div>
          <input
            type="text"
            class="MyInput"
            style="
              margin: 10px;
              width: 50% !important;
              border-radius: 0.5em !important;
            "
            name="subject"
            v-model="form.subject"
          />
        </label>
      </div>
      <br />

      <div style="display: flex">
        <label
          class="InputLabel"
          :style="`font-size: 18px;margin:0 10px 0 0;color:${
            form.allowDelay ? 'var(--mainColor)' : 'black'
          }`"
        >
          允许延迟提交 Allow Delay
        </label>
        <el-tooltip
          content="勾选此项, 那么在截至日期结束后, 同学们依旧可以提交"
          placement="top"
          effect="dark"
        >
          <el-switch v-model="form.allowDelay" />
        </el-tooltip>
      </div>
      <br />

      <div style="display: flex">
        <label
          class="InputLabel"
          style="font-size: 18px; margin: 10px 10px 10px 0px"
        >
          截止日期 Deadlines
        </label>
        <el-date-picker
          v-model="form.deadtime"
          type="datetime"
          placeholder="选择截止日期和时间"
          :time-arrow-control="true"
        />
        <!-- TODO 如果需要修改时区，请修改这里 -->
      </div>
      <br />

      <br />
      <div>
        <label for="submittype">
          <div class="InputLabel">备注* DESC (选填)</div>
          <textarea cols="30" rows="3" v-model="form.desc"
          :style="`resize:${config.textAreaMove ? 'both' : 'none'}`"
          ></textarea>
        </label>
      </div>
    </section>

    <div class="InputLabel" align="center">
      <button class="button primary" style="font-size:13px;" @click="submit">提交修改</button>
    </div>
  </div>
</template>



<script>
import { reactive, onMounted, computed, watch } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElNotification, ElLoading } from "element-plus";
import { formatTime } from "@/hook/format";

export default {
  name: "adjust",
  props : ['homeworkID'],
  emits : ["update"],
  setup(props, ctx) {
    let store = useStore();
    let router = useRouter();
    let homeworkID = props.homeworkID

    onMounted(() => {
      const loading = ElLoading.service({
        lock: true,
        text: "正在恢复填写数据中...",
        background: "rgba(0, 0, 0, 0.8)",
        customClass: "MyLoading",
      });
      let done1 = false, done2 = false;

      store.dispatch("groupCreateNum").then(function () {
        if (store.state.group.groupCreateNum) {
          let start = 0;
          let end = Math.min(store.state.group.groupCreateNum, 100);
          store.dispatch("groupCreated", { start, end }).then(function () {
            done1 = true
            if (done1 && done2)
                loading.close();
            if (store.state.group.groupCreated.length > 0) {
            } else {
              ElNotification({
                title: "Oops",
                message: "拉去初始化列表失败，错误信息: " + store.state.error,
              });
            }
          });
        } else {
          done1 = true
          if (done1 && done2)
            loading.close();
          let message;
          if (store.state.group.groupCreateNum == 0) {
            message = "小组数量为0，快去创建小组吧"
          } else {
            message =
              "不知道为啥，请求您创建的小组数量数量时出错了，错误信息: " +
              store.state.error;
          }
          ElNotification({ title: "Oops", message: message });
          return;
        }
      });
      
      store.dispatch("queryHomework", {homeworkID : homeworkID}).then(function() {
          if (store.state.opSuccess) {
              done2 = true
              if (done1 && done2)
                loading.close()
              store.state.opSuccess = undefined
              form.homeworkName = store.state.homework.homeworkQuery.name
              form.submitType.value = store.state.homework.homeworkQuery.type
              form.subject = store.state.homework.homeworkQuery.subject
              form.allowDelay = store.state.homework.homeworkQuery.CanSubmitAfterEnd
              form.deadtime = store.state.homework.homeworkQuery.endtime
              form.desc = store.state.homework.homeworkQuery.desc
              createdGroup.selvalue = store.state.homework.homeworkQuery.GroupID

              ElNotification({title: "模板恢复成功！", message: "这下你可以从提交前的状态开始修改了"})
          }
          else {
              done2 = true
              if (done1 && done2)
                loading.close()
              ElNotification({title: "Oops", message: "模板恢复失败, 错误原因: " + store.state.error})
          }
      })
    });

    let config = reactive({
      textAreaMove : store.state.textAreaMove,
    })

    let form = reactive({
      homeworkName: "",
      submitType: {
        value: "",
        options: [
          { value: "zip", label: "压缩包 (*.zip *.rar)" },
          {
            value: "source",
            label:
              "代码源文件 (*.py *.cpp *.c *.java *.v *.go *.php *.js *.ts *.sql)",
          },
          { value: "word", label: "word文档 (*.doc *docx)" },
          { value: "ppt", label: "幻灯片 (*.ppt *pptx *keynote)" },
          { value: "pdf", label: "PDF (*.pdf)" },
          { value: "data", label: "数据集 (*.csv *.tsv *.txt)" },
          {
            value: "picture",
            label: "图像 (*.png *.jpg *.jepg *svg *esp *pdf)",
          },
          { value: "model", label: "模型 (*.pth *.pkl *.onnx)" },
          {
            value: "config",
            label: "配置文件 (*.json *.yaml *.yml *.protcbuf)",
          },
        ],
        handleChange() {},
      },
      // 提交后应该更新首页的倒计时
      subject: "",
      allowDelay: false,
      deadtime: "",
      desc: "",
    });

    let createdGroup = reactive({
      selvalue: "",
      options: computed(() => {
        let groups = store.state.group.groupCreated,
          res = [];
        for (let i = 0; i < groups.length; ++i) {
          res.push({
            value: groups[i].id,
            label: `${groups[i].name}(ID ${groups[i].id})`,
          });
        }
        return res;
      }),

      handleChange() {
        // console.log(createdGroup.selvalue[0])
      },
    });

    function submit() {
      // check
      let name = form.homeworkName.trim();
      let type = form.submitType.value;
      let desc = form.desc.trim()
      let subject = form.subject.trim();
      if (form.deadtime.length == 0) {
        ElNotification({title: "Wrong!", message: "您貌似还有信息没有填完"})
        return
      }
      let endtime = formatTime(form.deadtime, "yyyy-MM-ddTHH:mm:ss+08:00")
      let canSubmitAfterEnd = form.allowDelay
      let groupID = createdGroup.selvalue;

      if (name.length == 0 || subject.length == 0 || endtime.length == 0) {
        ElNotification({ title: "Wrong!", message: "您貌似还有信息没有填完" });
        return;
      }
      if (
        name.includes(" ") ||
        subject.includes(" ") ||
        endtime.includes(" ")
      ) {
        ElNotification({ title: "Wrong!", message: "所填字段不能有空格！" });
        return;
      }
      if (type) { 
        if (typeof(type) != "string")
          type = type[0]
      } else {
        ElNotification({ title: "Wrong!", message: "请选择提交类型！" });
        return;
      }
      if (groupID) { groupID = groupID[0]
      } else {
        ElNotification({ title: "Wrong!", message: "请选择小组！" });
        return;
      }
      // 输入的时间必须比当前时间后
      let curtime = new Date();

      curtime = formatTime(curtime, "yyyy-MM-ddThh:mm:ss+08:00");
      if (curtime > endtime) {
        ElNotification({
          title: "Wrong!",
          message: "你发布的截止时间在过去，你是想让熵增颠倒吗？",
        });
        return;
      }

      const loading = ElLoading.service({
        lock: true,
        text: "正在提交请求中...",
        background: "rgba(0, 0, 0, 0.8)",
        customClass: "MyLoading",
      });
      store
        .dispatch("adjustHomework", {
          homeworkID,
          name,
          type,
          desc,
          subject,
          endtime,
          canSubmitAfterEnd,
          groupID,
        })
        .then(function () {
          if (store.state.opSuccess === true) {
            store.state.opSuccess = undefined;
            loading.close();
            ElNotification({
              title: "修改成功！",
              message: "我会重新刷新页面以获取最新的效果",
            });
            ctx.emit("update")
          } else {
            loading.close();
            ElNotification({
              title: "Oops",
              message: "修改失败了，错误信息: " + store.state.error,
            });
          }
        });
    }

    return {
      form,
      submit,
      createdGroup,
      config
    };
  },
};
</script>

<style>
.InputLabel {
  font-size: 20px;
  font-family: "Roboto Slab", serif;
}

.MySelect {
  width: 40% !important;
  font-family: "Roboto Slab", serif;
  font-size: 16px;
  text-align: center;
  border-radius: 3em !important;
  transition: all var(--focusTime) linear;
  -webkit-transition: all var(--focusTime) linear;
  -moz-transition: all var(--focusTime) linear;
}

el-time-picker button {
  border: 0ch !important;
}

.el-time-panel__footer {
  height: fit-content !important;
}

.el-time-panel__footer button {
  font-size: 8px;
}

.el-popper {
  font-family: "Roboto Slab", serif;
}

.el-popper button {
  font-size: 15px !important;
  border-radius: 1.5em !important;
  padding: 0 10px;
  box-shadow: 0 0 0 0 !important;
  margin: 1px;
}

.el-picker-panel__footer button {
  font-size: 8px !important;
  border-radius: 3em !important;
  padding: 20px !important;
  transition: all 0.3s linear;
  -moz-transition: all 0.3s linear;
  -webkit-transition: all 0.3s linear;
}

.el-picker-panel__footer button:hover {
  background-color: var(--mainColor);
  color: white;
  box-shadow: 0 0 8px 3px var(--mainColor) !important;
  transition: all 0.3s linear;
  -moz-transition: all 0.3s linear;
  -webkit-transition: all 0.3s linear;
}
</style>